import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Objects;

public class Window extends JFrame {
    private JTextField dateField, amountField, reasonField;
    private JButton addButton, deleteButton, updateButton, searchButton;
    private JComboBox<String> typeComboBox;
    private JTable detailsTable;
    private DefaultTableModel tableModel;
    private ArrayList<searchResult> results;



    public Window() {
        setTitle("财务管理");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(600, 300);
        setLocationRelativeTo(null);

        initializeComponents();
        addComponentsToFrame();
    }

    private void initializeComponents() {
        dateField = new JTextField(10);
        amountField = new JTextField(10);
        reasonField = new JTextField(15);

        addButton = new JButton("添加");
        deleteButton = new JButton("删除");
        updateButton = new JButton("更新");
        searchButton = new JButton("搜索");

        String[] types = {"收入", "支出"};
        typeComboBox = new JComboBox<>(types);

        // 创建表格模型和表格对象
        String[] columnNames = {"日期", "金额", "原因", "类型"};
        tableModel = new DefaultTableModel(columnNames, 0);
        detailsTable = new JTable(tableModel);
    }

    private void addComponentsToFrame() {
        JPanel inputPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.anchor = GridBagConstraints.WEST;
        gbc.insets = new Insets(5, 5, 5, 5);
        inputPanel.add(new JLabel("日期："), gbc);
        gbc.gridx++;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        inputPanel.add(dateField, gbc);

        gbc.gridx = 0;
        gbc.gridy++;
        gbc.fill = GridBagConstraints.NONE;
        inputPanel.add(new JLabel("金额："), gbc);
        gbc.gridx++;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        inputPanel.add(amountField, gbc);

        gbc.gridx = 0;
        gbc.gridy++;
        gbc.fill = GridBagConstraints.NONE;
        inputPanel.add(new JLabel("原因："), gbc);
        gbc.gridx++;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        inputPanel.add(reasonField, gbc);

        gbc.gridx = 0;
        gbc.gridy++;
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        gbc.fill = GridBagConstraints.NONE;
        inputPanel.add(new JLabel("类型："), gbc);
        gbc.gridx++;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        inputPanel.add(typeComboBox, gbc);

        gbc.gridx = 0;
        gbc.gridy++;
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        gbc.fill = GridBagConstraints.NONE;
        inputPanel.add(addButton, gbc);

        gbc.gridy++;
        inputPanel.add(deleteButton, gbc);

        gbc.gridy++;
        inputPanel.add(updateButton, gbc);

        gbc.gridy++;
        inputPanel.add(searchButton, gbc);

        add(inputPanel, BorderLayout.WEST);
        add(new JScrollPane(detailsTable), BorderLayout.CENTER);



        // 添加按钮点击事件监听器
        addButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String date = dateField.getText();
                String reason = reasonField.getText();
                String type = (String) typeComboBox.getSelectedItem();
                String amountText = amountField.getText();

                Tool tool = new Tool();
                double amount;

                try {
                    amount = Double.parseDouble(amountText);
                } catch (NumberFormatException ex){
                    JOptionPane.showMessageDialog(Window.this, "金额输入不正确", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                if (!tool.isValidDate(date)) {
                    JOptionPane.showMessageDialog(Window.this, "日期格式不正确,应该为：yyyy-mm-dd", "错误", JOptionPane.ERROR_MESSAGE);
                    return; // 如果日期格式不正确，停止执行后续操作
                }

                if (amount < 0) {
                    JOptionPane.showMessageDialog(Window.this, "金额输入不正确", "错误", JOptionPane.ERROR_MESSAGE);
                    return; // 如果金额不正确，停止执行后续操作
                }

                if (Objects.equals(type, "支出"))
                    tool.updateMainWindowData2(amount);
                if (Objects.equals(type, "收入"))
                    tool.updateMainWindowData1(amount);

                if (!date.isEmpty() && !amountText.isEmpty() && !reason.isEmpty()) {
                    String[] rowData = {date, amountText, reason, type};
                    tableModel.addRow(rowData);

                    // 清空输入框
                    dateField.setText("");
                    amountField.setText("");
                    reasonField.setText("");

                } else {
                    JOptionPane.showMessageDialog(Window.this,
                            "请输入完整的信息", "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        });


        deleteButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int selectedRow = detailsTable.getSelectedRow();
                if (selectedRow != -1) { // 判断选中行是否存在
                    double amount = Double.parseDouble((detailsTable.getValueAt(selectedRow, 1)).toString());
                    String type = (String) detailsTable.getValueAt(selectedRow, 3);
                    tableModel.removeRow(selectedRow);

                    Tool tool = new Tool();
                    if(Objects.equals(type, "支出"))
                        tool.updateMainWindowData3(amount);
                    if(Objects.equals(type, "收入"))
                        tool.updateMainWindowData4(amount);
                } else {
                    JOptionPane.showMessageDialog(Window.this,
                            "请选择要删除的行", "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        });


        updateButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int selectedRow = detailsTable.getSelectedRow();
                double upAmount = Double.parseDouble((detailsTable.getValueAt(selectedRow, 1)).toString());
                String upType = (String) detailsTable.getValueAt(selectedRow, 3);

                String amountText = amountField.getText();

                double amount;

                if (selectedRow != -1) {
                    String date = dateField.getText();

                    String reason = reasonField.getText();

                    try {
                        amount = Double.parseDouble(amountText);
                    } catch (NumberFormatException ex){
                        JOptionPane.showMessageDialog(Window.this, "金额输入不正确", "错误", JOptionPane.ERROR_MESSAGE);
                        return;
                    }


                    if (!date.isEmpty() && !amountText.isEmpty() && !reason.isEmpty()) {
                        tableModel.setValueAt(date, selectedRow, 0);
                        tableModel.setValueAt(amount, selectedRow, 1);
                        tableModel.setValueAt(reason, selectedRow, 2);

                        Tool tool = new Tool();
                        if (!tool.isValidDate(date)) {
                            JOptionPane.showMessageDialog(Window.this, "日期格式不正确,应该为：yyyy-mm-dd", "错误", JOptionPane.ERROR_MESSAGE);
                            return; // 如果日期格式不正确，停止执行后续操作
                        }
                        if (amount < 0) {
                            JOptionPane.showMessageDialog(Window.this, "金额输入不正确", "错误", JOptionPane.ERROR_MESSAGE);
                            return; // 如果金额不正确，停止执行后续操作
                        }
                        if(Objects.equals(upType, "支出"))
                            tool.updateMainWindowData5(amount,upAmount);
                        if(Objects.equals(upType, "收入"))
                            tool.updateMainWindowData6(amount,upAmount);

                        // 清空输入框
                        dateField.setText("");
                        amountField.setText("");
                        reasonField.setText("");
                    } else {
                        JOptionPane.showMessageDialog(Window.this,
                                "请输入完整的信息", "错误", JOptionPane.ERROR_MESSAGE);
                    }
                } else {
                    JOptionPane.showMessageDialog(Window.this,
                            "请选择要更新的行", "错误", JOptionPane.ERROR_MESSAGE);
                }



            }
        });

        searchButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String keyword = JOptionPane.showInputDialog(Window.this,
                        "请输入要搜索的关键词");
                if (keyword != null && !keyword.isEmpty()) {
                    results = new ArrayList<>(); // 存储搜索结果

                    for (int i = 0; i < tableModel.getRowCount(); i++) {
                        String date = tableModel.getValueAt(i, 0).toString();
                        String amount = tableModel.getValueAt(i, 1).toString();
                        String reason = tableModel.getValueAt(i, 2).toString();
                        String type = tableModel.getValueAt(i, 3).toString();

                        if (date.contains(keyword) || reason.contains(keyword) || type.contains(keyword)) {
                            results.add(new searchResult(date, amount,type, reason));
                        }
                    }

                    if (!results.isEmpty()) {
                        // 创建新界面展示搜索结果
                        JFrame searchResultFrame = new JFrame("搜索结果");
                        searchResultFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

                        String[] columnNames = {"日期", "金额", "原因","类型"};
                        String[][] data = new String[results.size()][4];
                        for (int i = 0; i < results.size(); i++) {
                            searchResult result = results.get(i);
                            data[i] = new String[]{result.getTime(), result.getAmount(), result.getReason(), result.getType()};
                        }

                        JTable searchResultTable = new JTable(data, columnNames);
                        JScrollPane scrollPane = new JScrollPane(searchResultTable);
                        searchResultFrame.getContentPane().add(scrollPane);

                        searchResultFrame.pack();
                        searchResultFrame.setVisible(true);
                    } else {
                        JOptionPane.showMessageDialog(Window.this, "未找到匹配的记录");
                    }
                }
            }
        });

    }

}
